package tools

import (
	"log"
	"prometheus_import_consul/global"
	"time"

	"github.com/hashicorp/consul/api"
)

// StartTTLHeartbeat 开始发送TTL心跳
func StartTTLHeartbeat(checkID, note string, interval time.Duration) {
	ticker := time.NewTicker(interval)
	for range ticker.C {
		err := global.ConsulClient.Agent().UpdateTTL(checkID, note, "pass")
		if err != nil {
			log.Fatalf("Error updating TTL for %s: %s\n", checkID, err)
			// 根据你的需求，这里可以添加错误处理逻辑，比如重试或者发送警告
		} else {
			log.Printf("TTL for %s updated successfully\n", checkID)
		}
	}
}
func Add_Icmp(ip, env, IcmpType, businesscode string) {
	// 构造服务注册的配置
	checkID := global.Config.Consul.ServiceName[1] + "_" + ip
	registration := &api.AgentServiceRegistration{
		ID:      checkID,                             // 唯一服务ID
		Name:    global.Config.Consul.ServiceName[1], // 服务名称
		Address: ip,
		Tags:    []string{global.Config.Consul.ServiceName[1] + ip, "prometheus-icmp"},
		Meta: map[string]string{
			"env":          env,
			"IcmpType":     IcmpType,
			"businesscode": businesscode,
		},
		Check: &api.AgentServiceCheck{
			TTL:                            "10s",
			DeregisterCriticalServiceAfter: "5m",
		},
	}
	// 使用Consul客户端注册服务
	if err := global.ConsulClient.Agent().ServiceRegister(registration); err != nil {
		log.Fatalf("Error registering host with Consul:%v\n", err)
		return
	}

	log.Printf("icmp %s registered successfully\n", registration.ID)
	// 开始发送心跳
	go StartTTLHeartbeat(checkID, "TTL check passed", 5*time.Second) // 5秒钟发送一次心跳，确保在10秒的TTL之前
}
